//
//  BIndacatorView.m
//  iLook
//
//  Created by Zhang Yinghui on 11-7-28.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BKIndicator.h"
#import "UILabel+x.h"
#import "NSAttributedString+x.h"

#define THEME_INDICATOR_TEXT_FONT  [UIFont boldSystemFontOfSize:16]
#define THEME_INDICATOR_ICON_WIDTH  32
#define THEME_INDICATOR_BG_COLOR   [UIColor colorWithWhite:0.2 alpha:0.8]
#define MSG_CONTENT_VIEW_TAG 999

#define TIP_FONT [UIFont systemFontOfSize:12]
#define TIP_BACKGROUND_COLOR [UIColor colorWithWhite:0.2 alpha:0.9]
#define TIP_TEXT_COLOR [UIColor colorWithWhite:0.95 alpha:1]

static UIView * _msgView = nil;
static UIView * _tipView = nil;

@implementation BKIndicator
+ (UIView *)createIndicator:(BOOL)withIndicator icon:(UIImage *)icon message:(NSString *)msg inView:(UIView *)container{
    float iconWidth = 0;
    float iconHeight = 0;
    if (icon) {
        withIndicator = NO;
    }
    if (withIndicator) {
        iconWidth = THEME_INDICATOR_ICON_WIDTH;
        iconHeight = THEME_INDICATOR_ICON_WIDTH;
    }else if (icon) {
        iconWidth = 2*THEME_INDICATOR_ICON_WIDTH;
        iconHeight = THEME_INDICATOR_ICON_WIDTH;
    }
    CGSize size = [NSAttributedString sizeOfString:msg withFont:THEME_INDICATOR_TEXT_FONT];
    float k = withIndicator?(2*iconWidth/2):0;
    float w = sqrt(4*size.width*size.height/3+k*k)+k+10;
    
    size = [NSAttributedString sizeOfString:msg withFont:THEME_INDICATOR_TEXT_FONT constrainedToSize:CGSizeMake(w, CGFLOAT_MAX)];
    float h = size.height + (withIndicator?iconWidth:0);
    h = MAX(h, w*3/4);
    w = MAX(w, 120);
    float padding = 10;
    CGRect rect = CGRectMake(0, 0, w+4*padding, h+4*padding);
    if (size.width == 0 && withIndicator) {
        padding = 5;
        rect.size = CGSizeMake(iconWidth+2*padding, iconWidth+2*padding);
    }
    
	UIView *view = /*AUTORELEASE*/([[UIView alloc] initWithFrame:rect] );
	view.backgroundColor = THEME_INDICATOR_BG_COLOR;
	view.layer.cornerRadius = 8.0;
    
    rect = CGRectInset(rect, padding, padding);
    if (withIndicator || icon) {
        CGRect r = CGRectMake(rect.origin.x+(rect.size.width-iconWidth)/2, rect.origin.y, iconWidth, iconHeight);
        UIView *iconView = nil;
        if (withIndicator) {
            iconView = /*AUTORELEASE*/([[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]);
            [iconView setFrame:r];
            [(id)iconView startAnimating];
        }else{
            iconView = [[UIButton alloc] initWithFrame:r];
            [(id)iconView setImage:icon forState:UIControlStateNormal];
        }
        
        [view addSubview:iconView];
        rect.origin.y += iconHeight;
        rect.size.height -= iconHeight;
    }
    UILabel *label = createLabel(rect, THEME_INDICATOR_TEXT_FONT, nil, [UIColor whiteColor], [UIColor blackColor], CGSizeMake(0, -1), NSTextAlignmentCenter, 0, NSLineBreakByTruncatingTail);
	label.text = msg;
	label.textColor = [UIColor whiteColor];
	[view addSubview:label];
    [view setTag:MSG_CONTENT_VIEW_TAG];
    
    if (_msgView && [_msgView superview]) {
        [_msgView removeFromSuperview];
    }
    ////
    _msgView = [[UIView alloc] initWithFrame:container.bounds];
    _msgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    view.center = CGPointMake(_msgView.bounds.size.width/2, _msgView.bounds.size.height*0.4);
    view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
    if (container == [self currentWindow]) {
        id rootControllr = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        CGAffineTransform containerTransform = container.transform;
        if (rootControllr && (containerTransform.tx==0 || containerTransform.ty==0 )) {
            _msgView.transform = CGAffineTransformIdentity;
            _msgView.transform = [rootControllr view].transform;
        }
    }
    [_msgView addSubview:view];
    [container addSubview:_msgView];
    [container bringSubviewToFront:_msgView];
    return  view;
    
}
+ (UIView *)showMessage:(NSString *)msg duration:(float) t inView:(UIView *)view completion:(void (^)(void))callback{
    [self createIndicator:NO message:msg inView:view];
	[self fadeOutWithDelay:t completion:callback];
	return _msgView;
	
}
+ (UIWindow *)currentWindow{
    UIWindow *window = nil;
    for (UIWindow * w in [[UIApplication sharedApplication] windows]) {
        window = window?:w;
        if (w.windowLevel > window.windowLevel) {
            window = w;
        }
    }
    return window;
}
+ (UIView *)createIndicator:(BOOL)withIndicator message:(NSString *)msg inView:(UIView *)container{
    return [self createIndicator:withIndicator icon:nil message:msg inView:container];
}
+(UIView *)showMessage:(NSString *)msg duration:(float)t completion:(void (^)(void))callback{
    UIView *view = [self currentWindow];
    return [BKIndicator showMessage:msg duration:t inView:view completion:callback];
}

+ (UIView *)showMessage:(NSString *)msg inView:(UIView *)view{
    return [self showMessage:msg icon:nil inView:view];
}
+ (UIView *)showMessageAndFadeOut:(NSString *)msg completion:(void (^)(void))callback{
    return [self showMessage:msg duration:3.0 completion:callback];
}
+ (UIView *)showMessage:(NSString *)msg icon:(UIImage *)icon inView:(UIView *)view{
    [self createIndicator:YES icon:icon message:msg inView:view];
    return _msgView;
}

+ (UIView *)showMessage:(NSString *)msg{
    return [BKIndicator showMessage:msg inView:[self currentWindow]];
}
+ (void)fadeOutWithDelay:(float)t completion:(void (^)(void))callback{
    if (!_msgView && ![_msgView superview]) {
        ////
        return;
    }
    [UIView animateWithDuration:0.2 delay:t 
						options:UIViewAnimationOptionCurveEaseOut
					 animations:^{
                         UIView *contentView = [_msgView viewWithTag:MSG_CONTENT_VIEW_TAG];
                         if (!contentView) {
                             return ;
                         }
						 CGAffineTransform _transform = CGAffineTransformMakeScale( 0.1 , 0.1 );
						 [contentView setTransform:_transform];
						 contentView.alpha = 0;
                         
					 } 
					completion :^(BOOL finished){	
                        [_msgView removeFromSuperview];
                        if (callback) {
                            callback();
                        }
                        ////
					}];
}
+ (void)fadeOutWithCompletion:(void (^)(void))callback{
    [self fadeOutWithDelay:1.0 completion:callback];
}

//+ (UIView *)showTips:(NSString*)tips frame:(CGRect)labelFrame inView:(UIView *)container duration:(float) duration{
//    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
//    label.font = TIP_FONT;
//    label.backgroundColor = TIP_BACKGROUND_COLOR;
//    label.textColor = TIP_TEXT_COLOR;
//    label.layer.cornerRadius = labelFrame.size.height/2;
//    label.clipsToBounds = YES;
//    label.textAlignment = NSTextAlignmentCenter;
//    label.text = tips;
//    [container addSubview:label];
//    if (duration>0) {
//        [UIView animateWithDuration:0.2
//                              delay:duration
//                            options:UIViewAnimationOptionTransitionNone
//                         animations:^{
//                             label.alpha = 0;
//                         }
//                         completion:^(BOOL finished) {
//                             [label removeFromSuperview];
//                         }];
//    }
//    if (_tipView && _tipView.superview) {
//        [_tipView removeFromSuperview];
//    }
//    _tipView = label;
//    return label;
//}
//+ (UIView *)showTips:(NSString*)tips bottom:(CGFloat)height inView:(UIView *)container duration:(float) duration{
//    CGSize tipSize = [tips sizeWithAttributes:@{NSFontAttributeName:TIP_FONT}];
//    CGRect labelFrame = CGRectMake((container.bounds.size.width-tipSize.width-10)/2, container.bounds.size.height - height - tipSize.height-6, tipSize.width+20,tipSize.height+6);
//    return [self showTips:tips frame:labelFrame inView:container duration:duration];
//}
//+ (UIView *)showTips:(NSString*)tips top:(CGFloat)height inView:(UIView *)container duration:(float) duration{
//    CGSize tipSize = [tips sizeWithAttributes:@{NSFontAttributeName:TIP_FONT}];
//    CGRect labelFrame = CGRectMake((container.bounds.size.width-tipSize.width-10)/2, height, tipSize.width+20,tipSize.height+6);
//    return [self showTips:tips frame:labelFrame inView:container duration:duration];
//}
//+ (UIView *)showTips:(NSString*)tips style:(BKTipStyle)style inView:(UIView *)container duration:(float) duration{
//    if (style == BKTipStyleTop) {
//        return [self showTips:tips top:88.0 inView:container duration:duration];
//    }
//    return [self showTips:tips bottom:88.0 inView:container duration:duration];
//}
+ (void)tipFadeOutWithDelay:(float)t completion:(void (^)(void))callback{
    if (!_tipView && ![_tipView superview]) {
        return;
    }
    [UIView animateWithDuration:0.2 delay:t
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         _tipView.alpha = 0;
                     }
                    completion :^(BOOL finished){
                        [_tipView removeFromSuperview];
                        if (callback) {
                            callback();
                        }
                    }];
}

+ (UIView *)showTips:(NSString*)tips offsetY:(CGFloat)offsetY inView:(UIView *)container duration:(float) duration completion:(void (^)(void))callback{
    CGSize tipSize = [tips sizeWithAttributes:@{NSFontAttributeName:TIP_FONT}];
    CGRect labelFrame = CGRectMake((container.bounds.size.width-tipSize.width-10)/2, offsetY, tipSize.width+20,tipSize.height+6);
    
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = TIP_FONT;
    label.backgroundColor = TIP_BACKGROUND_COLOR;
    label.textColor = TIP_TEXT_COLOR;
    label.layer.cornerRadius = labelFrame.size.height/2;
    label.clipsToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = tips;
    [container addSubview:label];
    if (duration>0) {
        [UIView animateWithDuration:0.2
                              delay:duration
                            options:UIViewAnimationOptionTransitionNone
                         animations:^{
            label.alpha = 0;
        }
                         completion:^(BOOL finished) {
            [label removeFromSuperview];
            if (callback) {
                callback();
            }
        }];
    }
    if (_tipView && _tipView.superview) {
        [_tipView removeFromSuperview];
    }
    _tipView = label;
    return label;
}
+ (UIView *)showTips:(NSString*)tips inView:(UIView *)container  duration:(float) duration completion:(void (^)(void))callback{
    CGFloat offsetY = container.bounds.size.height - 88;
    return [self showTips:tips offsetY:offsetY inView:container duration:duration completion:callback];
}
+ (UIView *)showTips:(NSString*)tips duration:(float) duration completion:(void (^)(void))callback{
    UIView *container = [self currentWindow];
    return [self showTips:tips inView:container duration:duration completion:callback];
}
@end
